package main

import (
	"fmt"
	"net"

	"task/config"
	"task/driver"
	pb "task/pb/dispatch"
	service "task/service/dispatch"

	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc"
)

func main() {
	// 日志初始化
	log.SetFormatter(&log.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05.000",
	})
	// 初始化DB
	driver.InitEngine()
	// 初始化调度事件
	service.InitDispatchEvent()
	// 缓存并定时更新DAG信息
	service.InitDagMap()
	// 初始化消息队列
	driver.InitPulsarClient()
	defer driver.PulsarClient.Close()
	// 初始化执行消息生产者
	driver.InitExecuteProducer()
	defer driver.ExecuteProducer.Close()
	// 开启metrics服务
	go driver.StartMetricsServer()
	// 创建并运行grpc服务
	addr := fmt.Sprintf(":%d", config.Conf.TaskDispatch.GrpcPort)
	lis, err := net.Listen("tcp", addr)
	if err != nil {
		log.Panic("Failed to listen:", err)
	}
	defer lis.Close()
	// 使用中间件 引入监控
	grpcServer := grpc.NewServer(grpc.UnaryInterceptor(service.DispatchUnaryServerInterceptor))
	pb.RegisterDispatchServiceServer(grpcServer, service.NewDispatchServer())
	if err = grpcServer.Serve(lis); err != nil {
		log.Panic("Failed to start dispatch grpc server:", err)
	}
}
